package com.car.ui;

import java.util.HashMap;
import java.util.Random;
import java.util.Vector;

import com.car.comm.Logger;
import com.car.comm.Variable;
import com.car.framework.FrameActivity;
import com.car.framework.TestMapping;
import com.car.postoffice.CAddress;
import com.car.postoffice.CMail;
import com.car.postoffice.CMailHeader;
import com.car.postoffice.CMailReply;
import com.car.postoffice.SendException;
import com.car.postoffice.TPostMark;
import com.car.postoffice.UnSupportedScheme;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class CarActivity extends FrameActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button btnTest = (Button)this.findViewById(R.id.button_test);
        btnTest.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				System.out.println("onClick");
				for(int index = 0; index < 10; ++index){
					CMail mail = new CMail(CarActivity.this.addr, 
									   new CAddress(Variable.httpGetScheme, "www.baidu.com"));
					mail.getHeader().setMailId(index + 1);
					mail.getHeader().setMailType("http");
					try {
						final TPostMark mark = office.SendMail(mail, Variable.levelNormal, new TestMapping());
						map.put(mail.getHeader(), mark);
						queue.add(mark);
					} catch (SendException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (UnSupportedScheme e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					Random rand = new Random();
					int i = rand.nextInt(queue.size());
					if(i % 3 == 1){
						Logger.LogDebug("Cancel Mail");
						office.CancelMail(queue.get(i));
						queue.remove(i);
					}
				}
			}
        	
        });
        
    }
    
    @Override
    public void onStart(){
    	super.onStart();
    }
    
    @Override
    public void onResume(){
    	super.onResume();
    }
    
    @Override
    public void onPause(){
    	super.onPause();
    }
    
    @Override
    public void onStop(){
    	super.onStop();
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    	super.onActivityResult(requestCode, resultCode, data);  
    }  
    
    @Override
    public void onDestroy(){
    	super.onDestroy();
    }
    
    HashMap<CMailHeader, TPostMark> map = new HashMap<CMailHeader, TPostMark>();
    Vector<TPostMark> queue = new Vector<TPostMark>();
    public void HandleReply(CMailReply reply){
    	TPostMark mark = map.get(reply.getHeader());
    	if(mark != null){
    		queue.remove(mark);
    		map.remove(mark);
    	}
    	Logger.LogDebug("=====HandleReply " + reply.getHeader() + "=======");
    }
}